<template>
  <div class="app-container home">
    <div>
      <el-row v-if="!this.userRole.includes('admin') && !this.userRole.includes('administrator')" :gutter="20">
        <el-col :sm="24" :lg="24">
          <div class="app-container">
            <el-table v-loading="loading" :data="noticeList">
              <el-table-column label="序号" align="center" prop="noticeId" width="150" />
              <el-table-column
                label="公告标题"
                align="center"
                prop="noticeTitle"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="公告类型" align="center" prop="noticeType" width="150">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_notice_type" :value="scope.row.noticeType"/>
                </template>
              </el-table-column>
              <el-table-column label="创建者" align="center" prop="createBy" width="150" />
              <el-table-column label="创建时间" align="center" prop="createTime" width="150">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="openDetailDialog(scope.row.noticeId)"
                  >查看</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!--通知公告详情 -->
            <el-dialog :title="form.noticeTitle" :visible.sync="openDetail" width="800px" append-to-body>
              <div style="margin-top:-20px;margin-bottom:10px;">
                <el-tag size="mini" effect="dark" type="warning" v-if="form.noticeType==2">公告</el-tag>
                <el-tag size="mini" effect="dark" v-else>信息</el-tag>
                <span style="margin-left:20px;">{{form.createTime}}</span>
              </div>
              <div v-loading="loadingDetail" class="content">
                <div v-html="form.noticeContent" style="margin-left:0px;margin-right:76px" class="ql-editor"></div>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="closeDetail"> 关 闭 </el-button>
              </div>
            </el-dialog>
          </div>
        </el-col>
      </el-row>
      <dv-border-box-2 v-if="this.userRole.includes('admin') || this.userRole.includes('administrator')" v-loading="monitorLoading"
                       element-loading-background="rgba(0, 0, 0, 0.2)"
                       element-loading-text="数据正在加载中"
                       element-loading-spinner="el-icon-loading"
                       style="margin: 8px;background-color: #F6F6F6; height: 1000px">
        <el-container>
          <el-header style="display: flex;justify-content: center;margin-top: 2%">
            <dv-decoration-11 style="width:250px;height:60px;">新能源充电桩监控</dv-decoration-11>
          </el-header>
          <el-container style="display: flex; justify-content: center">
            <el-main style="width: 40%">
              <el-header style="height: 165px;display: flex; justify-content: center">
                <dv-border-box-8 style="width: 60%">
                  <div style="padding-top: 10px; display: flex; justify-content: center">充电桩情况</div>
                  <div style="margin-top: 5%; display: flex; justify-content: center">空闲：{{ chargePileIdleCount }}</div>
                  <div style="display: flex; justify-content: center">使用中：{{ chargePileInUseCount }}</div>
                  <div style="display: flex; justify-content: center">维修中：{{ chargePileInMaintenanceCount }}</div>
                  <div style="display: flex; justify-content: center">停用：{{ chargePileOutOfServiceCount }}</div>
                </dv-border-box-8>
                <dv-border-box-8 style="width: 40%; display: flex; justify-content: center">
                  <div style="padding-top: 10px; display: flex; justify-content: center">充电桩使用率</div>
                  <div style="display: flex; justify-content: center">
                    <dv-water-level-pond :config="onlineRate" style="margin: 0; width:80px;height:120px" />
                  </div>
                </dv-border-box-8>
              </el-header>
              <el-main>
                <dv-border-box-8 style="display: flex; justify-content: center">
                  <div style="padding-top: 10px; display: flex; justify-content: center">充电记录情况（近七天）</div>
                  <div style="width: 100%;height: 250px" id="main"></div>
                </dv-border-box-8>
              </el-main>
            </el-main>
            <el-main style="width: 60%">
              <dv-border-box-8 style="position:relative; width: 100%">
                <div align="center" style="padding-top: 1%">充电桩位置</div>
                <div id="mapPoint" style="width: 94%; height: 86%; position:absolute; left: 3%; top: 52%; transform:translateX(-50%); transform:translateY(-50%);"></div>
              </dv-border-box-8>
            </el-main>
          </el-container>
        </el-container>
        <div style="width: 100%">
          <div align="center">近七天充电桩维修情况</div>
          <div style="margin-top: 20px; display: flex; justify-content: center">
            <dv-scroll-board ref="scrollBoard" :config="repairRecordVoMonitorList" style="width:1200px;height:220px" />
          </div>
        </div>
      </dv-border-box-2>
    </div>

  </div>
</template>

<script>
  import {
    listNotice,
    getNotice,
  } from "@/api/system/notice";
  import {
    getMonitor,
  } from "@/api/chargepile/monitor";
  import AMapLoader from '@amap/amap-jsapi-loader'
  window._AMapSecurityConfig = {
    securityJsCode: '7b436841291cbd1488749eb10f1838a8' // '「申请的安全密钥」',
  }

  export default {
    name: "Index",
    dicts: ['sys_notice_status', 'sys_notice_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 详情加载
        loadingDetail: false,
        // 打开详情
        openDetail: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 公告表格数据
        noticeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          noticeTitle: undefined,
          createBy: undefined,
          status: 0
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          noticeTitle: [
            { required: true, message: "公告标题不能为空", trigger: "blur" }
          ],
          noticeType: [
            { required: true, message: "公告类型不能为空", trigger: "change" }
          ]
        },

        // 数据展示
        // 各个状态充电桩的数量
        chargePileIdleCount: undefined,
        chargePileInUseCount: undefined,
        chargePileInMaintenanceCount: undefined,
        chargePileOutOfServiceCount: undefined,
        // 最近其他充电次数
        dateList: [],
        chargeRecordsCount: [],
        // 设备在线率配置
        onlineRate: {
          data: [],
          waveNum: 1,
          waveHeight: 2,
          colors: ['#66BB6A']
        },
        // 最近七天的维修情况
        repairRecordVoList: [],
        repairRecordVoMonitorList: {
          header: ['设备编号', '设备类型', '报修人', '报修人电话', '报修内容', '报修时间'],
          data: [],
          index: true,
          columnWidth: [150, 150, 150, 250, 250, 150, 200],
          align: ['center', 'center', 'center', 'center','center','center','center'],
          carousel: 'page',
          waitTime: 3000
        },
        // 设备列表
        chargePileList: [],
        // loading
        monitorLoading: false,
        // 地图初始化数据
        mapForm: {
          showIndoorMap: true,
          resizeEnable: true,
          zoomEnable: true, // 地图是否可缩放，默认值为true
          dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
          doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
          zoom: 7, // 初始化地图级别
          center: [112.29, 30.98], // 初始化中心 湖北中心
          placeSearch: null, // 搜索关键字
          rotateEnable: true, // 地图是否可旋转
          features: ['bg', 'point', 'road','building'], // 设置地图上显示的元素种类
          layers: [],//使用多个图层
        }
      };
    },
    created() {
      this.getMonitor();
      this.getList();
      this.userRole = this.$store.state.user.roles
    },
    methods: {
      // 初始化地图
      initAMap() {
        AMapLoader.load({
          key: 'a033993f527d61fc06ac8adefd6c3b2c', // 申请好的Web端开发者Key，首次调用 load 时必填
          version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar', 'AMap.Geocoder', 'AMap.Marker',
            'AMap.CitySearch', 'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.InfoWindow', 'AMap.PlaceSearch'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap) => {
          // 设置标准图层
          let tileLayer = new AMap.TileLayer(); //高德默认标准图层
          this.mapForm.layers.push(tileLayer)

          // 获取到作为地图容器的DOM元素，创建地图实例
          this.map = new AMap.Map('mapPoint', // 设置地图容器id
            this.mapForm
          )

          if(this.form.postion !== undefined){
            this.setMarker(this.mapForm.center)
          }

          // 地图标尺
          this.map.addControl(new AMap.Scale());

          // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
          this.map.addControl(new AMap.ToolBar());

          const infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -30),
          });
          const that = this;
          for (let i = 0; i < this.chargePileList.length; i++) {
            const marker = new AMap.Marker({
              position: new AMap.LngLat(Number(this.chargePileList[i].postion.split(";")[0]), Number(this.chargePileList[i].postion.split(";")[1])),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              title: "你好"
            });
            marker.on('mouseover',function(e){
              console.log(e)
              infoWindow.setContent(
                `<div>
                        <div>
                          设备编号：${that.chargePileList[i].number}<br />
                        </div>
                        <div>
                          设备类型：${that.chargePileList[i].types === '0' ? "慢充" : "快充"}<br />
                        </div>
                      </div>`
              );
              infoWindow.open(that.map, [Number(that.chargePileList[i].postion.split(";")[0]), Number(that.chargePileList[i].postion.split(";")[1])]);
            })
            marker.on("mouseout", function (e) {
              console.log(e);
              infoWindow.close(that.map, [Number(that.chargePileList[i].postion.split(";")[0]), Number(that.chargePileList[i].postion.split(";")[1])]);
            });
            this.map.add(marker);
          }

        }).catch(e => {
          console.log("错误" + e)
        })
      },
      // 获取监控数据
      async getMonitor(){
        getMonitor().then((res) => {
          if(res.code === 200){
            const data = res.data;
            // 充电桩list
            this.chargePileList = data.chargePileList;
            // 各个状态充电桩的数量
            this.chargePileIdleCount = data.chargePileIdleCount
            this.chargePileInUseCount = data.chargePileInUseCount
            this.chargePileInMaintenanceCount = data.chargePileInMaintenanceCount
            this.chargePileOutOfServiceCount = data.chargePileOutOfServiceCount
            // 最近7天报修情况
            this.repairRecordVoList = data.repairRecordVoList;
            // 最近其他充电次数
            this.dateList = data.chargeRecordsMonitorVo.dateList;
            this.chargeRecordsCount = data.chargeRecordsMonitorVo.chargeRecordsCount;
            this.echartsInit()

            this.onlineRate.data[0] = res.data.onlineRate;
            this.onlineRate = { ...this.onlineRate }

            this.repairRecordVoList.forEach(item => {
              const arr = [];
              if(item.types === "0"){
                arr.push(item.pileNumber, "慢充", item.nickName, item.userPhone, item.requestContent, this.parseTime(item.requestTime))
              }
              if(item.types === "1"){
                arr.push(item.pileNumber, "快充", item.nickName, item.userPhone, item.requestContent, this.parseTime(item.requestTime))
              }
              this.repairRecordVoMonitorList.data.push(arr)
              this.repairRecordVoMonitorList = { ...this.repairRecordVoMonitorList }
            })

            this.initAMap()
          }
        })
      },
      //初始化echarts
      echartsInit() {
        //柱形图
        //因为初始化echarts 的时候，需要指定的容器 id='main'
        this.$echarts.init(document.getElementById('main')).setOption({
          xAxis: {
            type: 'category',
            data: this.dateList
          },
          yAxis: {
            // 刻度间隔为1
            minInterval: 1,
            type: 'value'
          },
          series: [{
            data: this.chargeRecordsCount,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(220, 220, 220, 0.8)'
            }
          }]
        })
      },
      /** 查询公告列表 */
      getList() {
        this.loading = true;
        listNotice(this.queryParams).then(response => {
          this.noticeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          noticeId: undefined,
          noticeTitle: undefined,
          noticeType: undefined,
          noticeContent: undefined,
          status: "0"
        };
        this.resetForm("form");
      },
      // 打开信息详情
      openDetailDialog(id) {
        this.openDetail = true;
        this.loadingDetail = true;
        getNotice(id).then(response => {
          this.form = response.data;
          this.openDetail = true;
          this.loadingDetail = false;
        });
      },
      // 取消按钮
      closeDetail() {
        this.titleDetail = "详情";
        this.openDetail = false;
        this.reset();
      },
    }
  };
</script>
